import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/views/Login.vue'
import layout from '@/views/Layout.vue'
import user from '@/views/User.vue'
import rights from '@/views/Rights.vue'
import roles from '@/views/Roles.vue'

Vue.use(VueRouter)


// 路由规则
const routes = [
  {
    path: '/',
    name: 'layout',
    component: layout,
    meta: {
      title: '首页'
    },
    children: [
      {
        path: '/users',
        name: 'users',
        meta: {
          title: '用户管理'
        },
        component: user
      },
      {
        path: '/rights',
        name: 'rights',
        meta: {
          title: '权限列表'
        },
        component: rights
      },
      {
        path: '/roles',
        name: 'roles',
        meta: {
          title: '角色列表'
        },
        component: roles
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: login
  }
]

const router = new VueRouter({
  routes
})


// 路由导航守卫

router.beforeEach((to, from, next) => {
  if (to.path == '/login') return next()
  // 获取缓存的token
  let token = localStorage.getItem('admin_token')
  if (!token) return next('/login')
  next()

  // to: 将要访问的地址
  // form: 现今访问的地址
  // next() 放行
})
export default router

// 后置守卫
router.afterEach((to, from)=> {
  console.log(to.meta);
  document.title = to.meta.title;
  sessionStorage.setItem('title',  to.meta.title)
}
)